<template>
  <div class="p-4">
    <h1 class="text-2xl font-bold mb-4">JSON 数据处理器</h1>

    <div class="mb-4">
      <label class="block mb-2">输入 JSON 数据:</label>
      <el-input type="textarea" v-model="jsonData" :rows="6" placeholder="请输入 JSON 数据"></el-input>
    </div>

    <div class="mb-4">
      <label class="block mb-2">输入表头信息 (以逗号分隔):</label>
      <el-input type="textarea" v-model="headers" :rows="3" placeholder="请输入表头信息"></el-input>
    </div>

    <div class="mb-4">
      <label class="block mb-2">输入搜索项 (以逗号分隔):</label>
      <el-input type="textarea" v-model="searchItems" :rows="3" placeholder="请输入搜索项"></el-input>
    </div>

    <div class="mb-4">
      <label class="block mb-2">输入需要过滤的文字 (以空格分隔):</label>
      <el-input v-model="specialStr" :rows="3" placeholder="输入需要过滤的文字"></el-input>
    </div>

    <el-button type="primary" @click="processData">处理数据</el-button>

    <div class="mt-4">
      <label class="block mb-2">处理结果:</label>
      <el-input type="textarea" v-model="result" :rows="10" placeholder="处理结果将显示在这里" readonly></el-input>
    </div>

    <div class="mt-4">
      <p class="block mb-2">字段:</p>
      <el-tag v-for="tag in originCol" type="info" class="cursor-pointer" :key="tag.prop" :disable-transitions="false"
        @click="addTag(tag)">
        {{ tag.originLabel }}
      </el-tag>
    </div>
    <div class="bg-[#dfdbd7] p-4 mt-4 drop-shadow-xl">
      <div class="mt-4">
        <p class="block mb-2">表头:</p>
        <el-tag v-for="tag in tipHeaders" disabled type="info" class="cursor-pointer" :key="tag"
          :disable-transitions="false" closable>
          {{ tag }}
        </el-tag>
      </div>
      <div class="mt-4">
        <p class="block mb-2">处理后:</p>
        <el-tag v-for="tag in processedCol" :type="curTag == tag ? 'danger' : 'primary'" class="cursor-pointer"
          :key="tag.prop" :disable-transitions="false" closable @close.stop="handleCloseTr(tag)" @click="choose(tag)">
          {{ tag.label }}
        </el-tag>
      </div>

      <div class="mt-4 flex items-center">
        <span class="mr-2">移动表头排序</span>
        <el-button-group>
          <el-button type="primary" @click="onSort(1)">首</el-button>
          <el-button type="primary" @click="onSort(2)">前</el-button>
          <el-button type="primary" @click="onSort(3)">后</el-button>
          <el-button type="primary" @click="onSort(4)">尾</el-button>
        </el-button-group>
      </div>
    </div>



    <div class="bg-[#dfdbd7] p-4 mt-4 drop-shadow-xl">
      <div class="mt-4">
        <p class="block mb-2">搜索:</p>
        <el-tag v-for="tag in searchItemsArray" type="info" class="cursor-pointer" :key="tag"
          :disable-transitions="false" closable>
          {{ tag }}
        </el-tag>
      </div>

      <div class="mt-4">
        <p class="block mb-2">处理后搜索:</p>
        <el-tag v-for="tag in searchCol" :type="curTag == tag ? 'danger' : 'primary'" class="cursor-pointer"
          :key="tag.prop" :disable-transitions="false" closable @close.stop="handleCloseSearch(tag)"
          @click="chooseSearch(tag)">
          {{ tag.label }}
        </el-tag>
      </div>
    </div>


    <!-- <div class="mt-4 flex items-center">
      <span class="mr-2">移动搜索排序</span>
      <el-button-group>
        <el-button type="primary" @click="onSortSearch(1)">首</el-button>
        <el-button type="primary" @click="onSortSearch(2)">前</el-button>
        <el-button type="primary" @click="onSortSearch(3)">后</el-button>
        <el-button type="primary" @click="onSortSearch(4)">尾</el-button>
      </el-button-group>
    </div> -->
    <div class="mt-4 flex items-center gap-2">
      <span class="text-nowrap">标签名</span> <el-input v-model="curTag.label"></el-input>
      <span class="text-nowrap">字典</span> <el-input v-model="curTag.dicName"></el-input>
      <span class="text-nowrap">快速搜索</span> <el-switch v-model="curTag.search"></el-switch>
      <span class="text-nowrap">搜索序号</span> <el-input v-model="curTag.searchOrder"></el-input>
      <span class="text-nowrap">搜素标签宽度</span> <el-input v-model="curTag.searchLabelWidth"></el-input>
    </div>

    <div class="my-4">
      <el-button @click="onCreate">生成代码</el-button>
    </div>

    <div class="mb-4">
      <el-input type="textarea" v-model="aimJson" :rows="4"></el-input>
    </div>
  </div>


</template>

<script>
import { addDicName, areSimilar, clone } from '@/comm/tableTooler'
export default {
  data() {
    return {
      jsonData: '',
      headers: '',
      searchItems: '',
      result: '',
      tipOrigin: '',
      tipHeaders: [],
      originCol: [],
      processedCol: [],
      searchItemsArray: [],
      curTag: { label: '' },
      aimJson: '',
      specialStr: ''
    };
  },
  mounted() {
    // 读取 localStorage 中的值并赋值
    this.jsonData = localStorage.getItem('jsonData') || '';
    this.headers = localStorage.getItem('headers') || '';
    this.searchItems = localStorage.getItem('searchItems') || '';
    this.specialStr = localStorage.getItem('specialStr') || '';

  },
  computed: {
    searchCol() {
      const ary = this.processedCol.filter(i => i.search);
      ary.sort((a, b) => (Number(b.searchOrder) || 0) - (Number(a.searchOrder) || 0));
      console.log("ary", ary);
      return ary;
    }

  },
  methods: {
    onSortSearch(direction) {
      // const index = this.searchCol.findIndex(col => col === this.curTag);

      // if (index === -1) return; // 如果当前标签不在 searchCol 中，直接返回

      // let newOrder = this.curTag.searchOrder || 0; // 获取当前的 searchOrder 值

      // switch (direction) {
      //   case 1: // 置顶
      //     newOrder = Math.max(...this.searchCol.map(col => col.searchOrder || 0)) + 1; // 设置为最大值 + 1
      //     break;
      //   case 2: // 向前
      //     if (newOrder > 0) newOrder--; // 如果大于 0，减 1
      //     break;
      //   case 3: // 向后
      //     newOrder++; // 增加 1
      //     break;
      //   case 4: // 置底
      //     newOrder = 0; // 设置为 0
      //     break;
      //   default:
      //     return; // 如果方向不在预期范围内，直接返回
      // }

      // // 更新当前标签的 searchOrder
      // this.curTag.searchOrder = newOrder;

      // // 重新排序 searchCol
      // this.searchCol.sort((a, b) => (Number(a.searchOrder) || 0) - (Number(b.searchOrder) || 0));
    },
    handleCloseSearch(tag) {
      tag.search = false
    },
    chooseSearch(tag) {
      this.curTag = tag;
    },
    handleCloseTr(tag) {
      console.log("tag", tag)
      this.processedCol = this.processedCol.filter(i => i != tag)
    },
    addTag(tag) {
      console.log("tag", tag)
      this.processedCol.push(tag)
    },
    choose(tag) {
      this.curTag = tag;
      console.log("cur", this.curTag)
    },
    onSort(direction) {
      const index = this.processedCol.findIndex(col => col === this.curTag);

      if (index === -1) return; // 如果当前标签不在 processedCol 中，直接返回

      let newIndex = index;

      switch (direction) {
        case 1: // 置顶
          newIndex = 0;
          break;
        case 2: // 向前
          if (index > 0) newIndex = index - 1;
          break;
        case 3: // 向后
          if (index < this.processedCol.length - 1) newIndex = index + 1;
          break;
        case 4: // 置底
          newIndex = this.processedCol.length - 1;
          break;
        default:
          return; // 如果方向不在预期范围内，直接返回
      }

      // 进行排序
      const movedItem = this.processedCol.splice(index, 1)[0]; // 移除当前项
      this.processedCol.splice(newIndex, 0, movedItem); // 在新位置插入
    },
    processData() {
      try {

        // 保存输入到 localStorage
        localStorage.setItem('jsonData', this.jsonData);
        localStorage.setItem('headers', this.headers);
        localStorage.setItem('searchItems', this.searchItems);
        localStorage.setItem('specialStr', this.specialStr);

        const json = JSON.parse(this.jsonData);
        this.originCol = [...json.column];


        // const headersArray = this.headers.split(',').map(header => header.trim());
        const headersArray = this.headers.split("\\n\\n").map(header => header.trim());
        console.log("headersArray", this.headers, headersArray)

        const searchItemsArray = this.searchItems.split(/[,，]/).map(item => item.trim());

        this.tipHeaders = headersArray
        this.searchItemsArray = searchItemsArray;

        const processedData = this.process([...this.originCol], headersArray, searchItemsArray);
        this.result = JSON.stringify(processedData, null, 2);

        this.processedCol = processedData

        const subColumn = json.group.map(item => {
          if (item.column[0].children) {
            return {
              type: "table",
              column: item.column[0].children.column
            }
          }
          return {
            type: "form",
            column: item.column
          }
        })

        console.log("subColumn", subColumn)




      } catch (error) {
        this.result = '处理失败: ' + error.message;
        console.log(error)
      }
    },
    removeParenthesesContent(input) {
      const regex = /[\u4e00-\u9fa5]+/;

      // 使用正则表达式的exec方法查找匹配项
      const match = regex.exec(input);

      // 如果找到匹配项，则返回匹配的中文字符，否则返回空字符串
      return match ? match[0] : '';
    },

    process(column, headers, searchItems) {
      const matchedColumns = [];

      const specialReplacements = this.specialStr ? this.specialStr.split(/\s+/) : []

      column.forEach(col => {
        let temp = ""
        const isMatch = headers.some(header => {
          //只保留中文部分
          const colLabel = this.removeParenthesesContent(col.label)
          if (colLabel === header || areSimilar(colLabel, header, specialReplacements)) {
            temp = header
            return true
          }

          return false;
        });

        col.originLabel = col.label
        if (isMatch) {
          col.label = temp
          matchedColumns.push(col);
        }
      });

      const result = {
        // id: jsonData.id,
        column: matchedColumns,
        // name: jsonData.name
      };

      matchedColumns.sort((a, b) => {
        return headers.indexOf(a.label) - headers.indexOf(b.label);
      });

      matchedColumns.forEach(col => {
        const header = headers.find(header => col.label === header || areSimilar(col.label, header, specialReplacements));
        if (header) {
          col.label = header;
        }
      });

      let searchOrder = 300;
      matchedColumns.forEach(col => {
        if (searchItems.includes(col.label)) {
          col.search = true;
          col.searchOrder = searchOrder;
          searchOrder -= 30;
        }
      });

      return matchedColumns;
    },
    onCreate() {
      const json = JSON.parse(this.jsonData);
      json.column = clone(this.processedCol)
      addDicName(json.column)
      this.aimJson = JSON.stringify(json, null, 2)
    }
  }
};
</script>

<style scoped>
/* 可以在这里添加自定义样式 */
</style>
